<?php

declare(strict_types=1);
namespace Service\StorageService;


use Service\BaseService;
use Service\Code\Normal;
use Service\Code\CodeBuilder;
use App\Model\BbcModel\Storage;
use App\Model\BbcModel\Mnuser;
use App\Model\BbcModel\StorageBondedOrder;
use App\Model\BbcModel\StorageBondedOrderDetail;
use App\Model\BbcModel\Stockin;
use App\Model\BbcModel\StockinDetail;
use App\Model\BbcModel\Goods;
use App\Model\BbcModel\PdaStockLoc;


class StockInService extends BaseService
{
    
    public function addData($cid,$mn_sid,$manager_id,$data) {
        $detaildata=[];
        $quantity=0;
        $money=0;
        $time=time();
        $code= CodeBuilder::getCode($mn_sid,'SI');
        $storage= Storage::instance()->info(['df'=>0,'cid'=>$cid,'mn_sid'=>$mn_sid,'store_type'=>0]);
        if(!$storage){
            return Normal::returnCode(Normal::FAIL, '仓库不存在', []);
        }
        $mnuserinfo= Mnuser::instance()->info(['id'=>$mn_sid]);
        $review=$mnuserinfo['is_review']??0;
        foreach ($data['goods'] as $key => $value) {
            $detaildata[]=[
                'cd'=>$time,
                'cid'=>$cid,
                'mn_sid'=>$mn_sid,
                'goods_id'=>$value['goods_id'],
                'quantity'=>$value['quantity'],
                'price'=>$value['price'],
                'money'=> $value['money'],
                'batch_no'=> $value['batch_no']?$value['batch_no']:'基准批次',
                'expire'=> $value['expire'],
                'bill_id'=>isset($value['bill_id'])?$value['bill_id']:0,
                'stock_loc'=>$value['stock_loc']
            ];
            $quantity= bcadd((string)$quantity, (string)$value['quantity']);
            $money= bcadd((string)$money,(string) $value['money'],2);
        }
        $stockindata=[
            'cd'=>$time,
            'cid'=>$cid,
            'mn_sid'=>$mn_sid,
            'status'=>$review==1?0:1,
            'code'=> $code,
            'type'=> $data['type'],
            'quantity'=>$quantity,
            'money'=>$money,
            'manager_id'=>$manager_id,
            'storage_id'=>$storage['id'],
            'remarks'=>$data['remarks']??'',
//            'approveuser'=>$review==1?0:$manager['id'],
//            'approvetime'=>$review==1?0:$time,
        ];
        if($data['type']==1){
            return Normal::returnCode(Normal::FAIL, '暂不支持');
        }elseif($data['type']==3){
            return Normal::returnCode(Normal::FAIL, '暂不支持');
        }elseif($data['type']==4&&$data['bill_id']!=0){
            $stockindata['bill_id']=$data['bill_id'];
            $bondedOrder=StorageBondedOrder::instance()->info(['id'=>$data['bill_id']]);
            if($bondedOrder['status']==2){
                return ['data' => '', 'code' => Normal::FAIL, 'message' => '该单据已全部收货'];
            }
            $stockindata['bill_code']=$bondedOrder['sn'];
        }
        
        try
        {
            Stockin::instance()->startTrans();
            $stockin= Stockin::instance()->add($stockindata);
            if( !$stockin) {
                Stockin::instance()->rollback();
                return Normal::returnCode(Normal::FAIL, '订单新增失败');
            }
            
            foreach ($detaildata as $key => $value) {
                if($review==1){
                    $detaildata[$key]['batch_id']=0;
                }else{
                    $stockExtra=[
                        'goods_id'=>$value['goods_id'],
                        'bill_type'=>1,
                        'bill_id'=>$stockin,
                        'bill_code'=>$code,
                        'num'=>$value['quantity'],
                        'batch_no'=>$value['batch_no'],
                        'expire'=>$value['expire'],
                        'price'=>$value['price'],
                        'stock_loc'=>$value['stock_loc'],
                        'manager_id'=>$manager_id
                    ];
                    $stockresult=StockService::instance()->addStock($cid,$mn_sid,$stockExtra);
                    if($stockresult['code']!= Normal::SUC){
                        Stockin::instance()->rollback();
                        return $stockresult;
                    }
                    $detaildata[$key]['batch_id']=$stockresult['data']['batch_id'];
//                    $cashgoodschange= CashGoodsChange::instance()->adddata([
//                        'cid'=>$cid,
//                        'mn_sid'=>$mn_sid,
//                        'goods_id'=>$value['goods_id']
//                    ]);
//                    if(!$cashgoodschange){
//                        self::rollback();
//                        return ['data' => '', 'code' => Normal::FAIL, 'message' => '新增失败,变更记录'];
//                    }
                }
                $detaildata[$key]['stockin_id']=$stockin;
                $addDetailData=$detaildata[$key];
                unset($addDetailData['stock_loc']);
                $stockindetail= StockinDetail::instance()->add($addDetailData);
                if(!$stockindetail){
                     Stockin::instance()->rollback();
                    return Normal::returnCode(Normal::FAIL, '订单详情新增失败');
                }
            }
            /**
             * 采购入库
             */
            if($data['type']==1){
                //todo
            }
            /**
             * 调拨入库
             */
            if($data['type']==3){
                //toddo
            }
            //保税入库，根据保展出库单
            if($data['type']==4&&$data['bill_id']!=0){
                $bondedOrderquantity=0;
                $bondedOrderGoodsquantity=0;
                foreach ($detaildata as $key => $value) {
                    $goods= Goods::instance()->info(['id'=>$value['goods_id']]);
                    $StorageBondedOrderDetailinfo= StorageBondedOrderDetail::instance()->info(['id'=>$value['bill_id']]);
                    $detail_receipt_quantity=bcadd((string)$StorageBondedOrderDetailinfo['receipt_quantity'],(string)$value['quantity']);
                    if($detail_receipt_quantity>$StorageBondedOrderDetailinfo['quantity']){
                        Stockin::instance()->rollback();
                        return Normal::returnCode(Normal::FAIL, '新增失败,商品'.$goods['name'].'入库数量大于单据商品数量');
                    }
                    $StorageBondedOrderDetailresult= StorageBondedOrderDetail::instance()->where(['id'=>$value['bill_id']])->increment('receipt_quantity',$value['quantity']);
                    if(!$StorageBondedOrderDetailresult){
                        Stockin::instance()->rollback();
                        return Normal::returnCode(Normal::FAIL, '新增失败,商品'.$goods['name'].'采购单详情数量更新有误');
                    }
                    $editDetailData=['status'=>1,'md'=>time()];
                    if($detail_receipt_quantity==$StorageBondedOrderDetailinfo['quantity']){
                        $editDetailData['status']=2;
                        $bondedOrderGoodsquantity=$bondedOrderGoodsquantity+1;
                    }
                    if($StorageBondedOrderDetailinfo['status']!=$editDetailData['status']){
                        $editDetailResult=StorageBondedOrderDetail::instance()->edit(['id'=>$value['bill_id']], $editDetailData);
                        if(!$editDetailResult){
                            Stockin::instance()->rollback();
                            return Normal::returnCode(Normal::FAIL, '新增失败,商品'.$goods['name'].'采购单详情状态更新有误');
                        }
                    }
                    $bondedOrderquantity+=$value['quantity'];
                }
                $bondedOrdertotalquantity=bcadd((string)$bondedOrder['receipt_quantity'], (string)$bondedOrderquantity);
                $bondedOrdertotalGoodsquantity=bcadd((string)$bondedOrder['receipt_goods_quantity'], (string)$bondedOrderGoodsquantity);
                $bondedOrdereditdata=['receipt_quantity'=>$bondedOrdertotalquantity,'receipt_goods_quantity'=>$bondedOrdertotalGoodsquantity];
                if($bondedOrdertotalquantity>$bondedOrder['quantity']){
                    Stockin::instance()->rollback();
                    return Normal::returnCode(Normal::FAIL, '新增失败,商品'.$goods['name'].'新增失败,原始单据数量有误');
                }elseif($bondedOrdertotalquantity==$bondedOrder['quantity']){
                    $bondedOrdereditdata['status']=2;
                }elseif($bondedOrdertotalquantity<$bondedOrder['quantity']){
                    $bondedOrdereditdata['status']=1;
                }
                $StorageBondedOrderresult= StorageBondedOrder::instance()->edit(['id'=>$data['bill_id']],$bondedOrdereditdata);
                if(!$StorageBondedOrderresult){
                    return Normal::returnCode(Normal::FAIL, '新增失败,商品'.$goods['name'].'新增失败,原始单据数量更新有误');
                }
            }
            Stockin::instance()->commit();
            return Normal::returnCode(Normal::SUC, '成功');
        } catch (\Exception $ex) {
            Stockin::instance()->rollback();
            return Normal::returnCode(Normal::FAIL, '失败'.$ex->getMessage());
        }
    }
    
    public function storageBondedOrderStockIn($cid,$mn_sid,$manager_id,$data) {
        if(!isset($data['goods'])||empty($data['goods'])){
            return Normal::returnCode(Normal::FAIL, '商品信息必传');
        }
        if(!isset($data['bill_id'])||empty($data['bill_id'])){
            return Normal::returnCode(Normal::FAIL, '原始单据信息必传');
        }
        $mn_user= Mnuser::instance()->info(['id'=>$mn_sid]);
        $goods=[];
        foreach ($data['goods'] as $key => $value) {
            if(!isset($value['skucode'])||empty($value['skucode'])){
                return Normal::returnCode(Normal::FAIL, '商品sku必传');
            }
            if($value['quantity']<=0){
                continue;
            }
            $goodsinfo= Goods::instance()->info([
                'df'=>0,
                'status'=>1,
                'skucode'=>$value['skucode'],
                'cid'=>$cid,
                //'supplier_id'=>$mn_user['supplier_id']
            ]);
            if(empty($goodsinfo)){
                return Normal::returnCode(Normal::FAIL, "商品SKU【{$value['skucode']}】商品未找到或已下架");
            }
            $bondOrderDetail= StorageBondedOrderDetail::instance()->info(['id'=>$value['bill_id']??0,'mn_sid'=>$mn_sid]);
            if(empty($bondOrderDetail)){
                return Normal::returnCode(Normal::FAIL, "商品SKU【{$value['skucode']}】原始单据未找到");
            }
            $stockLoc=[];
            if(isset($value['stock_loc'])&&!empty($value['stock_loc'])){
                $stockLoc= PdaStockLoc::instance()->info([
                    'cid'=>$cid,
                    'mn_sid'=>$mn_sid,
                    'code'=>$value['stock_loc'],
                    'status'=>1,
                    'df'=>0
                ]);
                if(empty($stockLoc)){
                   return Normal::returnCode(Normal::FAIL, "商品SKU【{$value['skucode']}】库位【{$value['stock_loc']}】未找到，或者已禁用"); 
                }       
            }
            $goods[]=[
                'goods_id'=>$goodsinfo['id'],
                'quantity'=>$value['quantity'],
                'price'=>$bondOrderDetail['price'],
                'money'=> bcmul((string)$value['quantity'],(string)$bondOrderDetail['price'],2),
                'bill_id'=>$value['bill_id'],
                'batch_no'=>$value['batch_no']??'基准批次',
                'expire'=>$value['expire'],
                'stock_loc'=>$stockLoc['id']??0
            ];
        }
        $addData=[
            'bill_id'=>$data['bill_id'],
            'type'=>4,
            'goods'=>$goods
        ];
        return $this->addData($cid, $mn_sid, $manager_id, $addData);
    }
}
